#!/usr/bin/env python

# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/437932
# Submitter: Graham Fawcett (other recipes)
# Last Updated: 2005/07/21
# Version no: 1.1 
# Author's notes: updated 2005.07.21, thanks to Jacob Oscarson
#
# Subsequent changes by Blair Conrad
#
# $Id: pyline.py,v 1.1 2005/08/08 16:10:04 bconrad Exp $

import sys
import re
import getopt

# parse options for module imports
opts, args = getopt.getopt(sys.argv[1:], 'm:f:')
opts = dict(opts)
if '-m' in opts:
    for imp in opts['-m'].split(','):
        locals()[imp] = __import__(imp.strip())

if '-f' in opts:
    input = file(opts['-f'])
else:
    input = sys.stdin    

cmd = ' '.join(args)
if not cmd.strip():
    cmd = 'line'                        # no-op

print cmd

codeobj = compile(cmd, 'command', 'eval')
write = sys.stdout.write

for numz, line in enumerate(input):
    line = line.rstrip()
    num = numz + 1
    words = [w for w in line.split(' ') if len(w)]
    result =  eval(codeobj, globals(), locals())
    if result is None or result is False:
        continue
    else:
        result = str(result)
    write(result)
    if not result.endswith('\n'):
        write('\n')
